﻿using Models.DataModel;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Models.DataStore
{
    public partial class Ctrl : Core
    {
        public async Task<int> AddCompany(Company company)
        {
            if (!string.IsNullOrEmpty(company.CompanyNumber))
            {
                company.CreatedOn = DateTime.Now;
                company.ModifiedOn = DateTime.Now;
                company.CompanyId = Guid.NewGuid();
                db.Companies.Add(company);
                return await db.SaveChangesAsync();
            }
            return 0;
        }
        public async Task<int> EditCompany(Company company)
        {
            try
            {
                db.Entry(company).State = EntityState.Modified;
                return await db.SaveChangesAsync();
            }
            catch
            {
                return 0;
            }
        }
        public async Task<int> DeleteCompany(Guid? companyId)
        {
            Company company = db.Companies.FirstOrDefault(c => c.CompanyId == companyId);
            db.Companies.Remove(company);
            return await db.SaveChangesAsync();
        }
        public IQueryable<Company> GetlstCompany()
        {
            var lstCompany = db.Companies;
            return lstCompany;
        }
        public Company GetCompany(Guid companyId)
        {
            var lstCompany = db.Companies.FirstOrDefault(c => c.CompanyId == companyId);
            return lstCompany;
        }

        public bool CheckExistCompanyNumber(string companyNumber)
        {
            return db.Companies.Count(c=>c.CompanyNumber==companyNumber) > 0;
        }
        public IQueryable<Company> GetlstCompanybyName(string companyName)
        {
            try
            {
                var lstPort = db.Companies.Where(c => c.Name.Contains(companyName));
                return lstPort;
            }
            catch (Exception ex) { return null; }
        }
    }
}
